{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Optimization without pyomo\n",
    "\n",
    "In this example we demonstrate the behaviour of the Linear Optimal Power Flow (LOPF) calculation without using pyomo. This requires to set `pyomo` to `False` in the `lopf` function. Then, the communication with the solvers happens via in-house functions which leads to a much faster solving process. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pypsa\n",
    "import pandas as pd\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = pypsa.examples.ac_dc_meshed(from_master=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Modify the network a bit: We set gas generators to non-extendable"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.generators.loc[n.generators.carrier == 'gas', 'p_nom_extendable'] = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add ramp limit"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.generators.loc[n.generators.carrier == 'gas', 'ramp_limit_down'] = 0.2\n",
    "n.generators.loc[n.generators.carrier == 'gas', 'ramp_limit_up'] = 0.2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add additional storage units (cyclic and non-cyclic) and fix one state_of_charge"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.add('StorageUnit', 'su', bus='Manchester', marginal_cost=10, inflow=50,\n",
    "      p_nom_extendable=True, capital_cost=10, p_nom=2000,\n",
    "      efficiency_dispatch=0.5,\n",
    "      cyclic_state_of_charge=True, state_of_charge_initial=1000)\n",
    "\n",
    "n.add('StorageUnit', 'su2', bus='Manchester', marginal_cost=10,\n",
    "      p_nom_extendable=True, capital_cost=50, p_nom=2000,\n",
    "      efficiency_dispatch=0.5, carrier='gas',\n",
    "      cyclic_state_of_charge=False, state_of_charge_initial=1000)\n",
    "\n",
    "n.storage_units_t.state_of_charge_set.loc[n.snapshots[7], 'su'] = 100"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add an additional store"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.add('Bus', 'storebus', carrier='hydro', x=-5, y=55)\n",
    "n.madd('Link', ['battery_power', 'battery_discharge'], '',\n",
    "       bus0=['Manchester', 'storebus'], bus1=['storebus', 'Manchester'],\n",
    "       p_nom=100, efficiency=.9, p_nom_extendable=True, p_nom_max=1000)\n",
    "n.madd('Store', ['store'], bus='storebus', e_nom=2000, e_nom_extendable=True,\n",
    "       marginal_cost=10, capital_cost=10, e_nom_max=5000, e_initial=100,\n",
    "       e_cyclic=True);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extra functionalities:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pypsa.linopt import get_var, linexpr, join_exprs, define_constraints "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One of the most important functions is linexpr which take one or more tuples of coefficient and variable pairs which should go into the left hand side (lhs) of the constraint. \n",
    "\n",
    "1. Add mimimum for state_of_charge"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def minimal_state_of_charge(n, snapshots):\n",
    "    vars_soc = get_var(n, 'StorageUnit', 'state_of_charge')\n",
    "    lhs = linexpr((1, vars_soc))\n",
    "    define_constraints(n, lhs, '>', 50, 'StorageUnit', 'soc_lower_bound')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2. Fix the ratio between ingoing and outgoing capacity of the Store"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fix_link_cap_ratio(n, snapshots):\n",
    "    vars_link = get_var(n, 'Link', 'p_nom')\n",
    "    eff = n.links.at['battery_power', 'efficiency']\n",
    "    lhs = linexpr((1, vars_link['battery_power']), (-eff, vars_link['battery_discharge']))\n",
    "    define_constraints(n, lhs, '=', 0, 'battery_discharge', attr='fixratio')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3. Every bus must in total produce the 20% of the total demand\n",
    "\n",
    "This requires the function `pypsa.linopt.join_exprs` which sums up arrays of linear expressions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fix_bus_production(n, snapshots):\n",
    "    total_demand = n.loads_t.p_set.sum().sum() \n",
    "    prod_per_bus = linexpr((1, get_var(n, 'Generator', 'p'))).groupby(n.generators.bus, axis=1).apply(join_exprs)\n",
    "    define_constraints(n, prod_per_bus, '>=', total_demand/5, 'Bus', 'production_share')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Combine them ..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def extra_functionalities(n, snapshots):\n",
    "    minimal_state_of_charge(n, snapshots)\n",
    "    fix_link_cap_ratio(n, snapshots)\n",
    "    fix_bus_production(n, snapshots)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "...and run the lopf with `pyomo=False`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.lopf(pyomo=False, extra_functionality=extra_functionalities, \n",
    "       keep_shadowprices=['Bus', 'battery_discharge', 'StorageUnit'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `keep_shadowprices` argument in the lopf now decides which shadow prices (SP) should be retrieved. It can either be set to `True`, then all SP are kept. It also can be a list of names of the constraints. Therefore the `name` argument in `define_constraints` is necessary, in our case 'battery_discharge', 'StorageUnit' and 'Bus'. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Analysing the constraints"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see if the system got our own constraints. We look at `n.constraints` which combines summarises constraints going into the linear problem"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.constraints"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The last three entries show our constraints. As 'soc_lower_bound' is time-dependent, the `pnl` value is set to `True`. \n",
    "\n",
    "Let's check whether out two custom constraint are fulfilled:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.links.loc[['battery_power', 'battery_discharge'], ['p_nom_opt']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.storage_units_t.state_of_charge"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.generators_t.p.groupby(n.generators.bus, axis=1).sum().sum()/n.loads_t.p.sum().sum()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looks good! Now, let's see which dual values were parsed. Therefore we have a look into `n.dualvalues` \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n.dualvalues"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Again we see the last two entries reflect our constraints (the values in the columns play only a minor role). Having a look what the values are:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pypsa.linopt import get_dual"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "get_dual(n, 'StorageUnit', 'soc_lower_bound')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_dual(n, 'battery_discharge', 'fixratio')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_dual(n, 'Bus', 'production_share')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Side note\n",
    "Some of the predefined constraints are stored in components itself like `n.lines_t.mu_upper` or `n.buses_t.marginal_price`, this is the case if their are designated columns are spots for those. All other dual are under the hook stored in `n.duals`"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}